<?php


namespace app\user\controller;


use think\Config;
use think\Db;
use think\Session;

class User extends Base
{

    public function Panel(){
        $UserInfo = UserInfo(['id'=>$this->user_id]);
        if ($UserInfo['level'] > 0){
            $UserInfo['level_name'] = LevelInfo(['id'=>$UserInfo['level']])['name'];
        }else{
            $UserInfo['level_name'] = '会员';
        }
        $team = Db::name('user_recommend')->where(['recommend_id'=>$this->user_id,'layer'=>['gt',0]])->count();

        //总奖金
        $total['reward_all'] = Db::name('finance')->where(['user_id'=>$this->user_id,'reward_type'=>['in',[7,8,9]]])->sum('num');
        $total['reward_7'] = Db::name('finance')->where(['user_id'=>$this->user_id,'reward_type'=>7])->sum('num');
        $total['reward_8'] = Db::name('finance')->where(['user_id'=>$this->user_id,'reward_type'=>8])->sum('num');
        $total['reward_9'] = Db::name('finance')->where(['user_id'=>$this->user_id,'reward_type'=>9])->sum('num');
        $total['recharge'] = Db::name('user_recharge')->where(['user_id'=>$this->user_id,'status'=>1])->sum('num');

        //最新公告
        $Notice = Db::name('notice')->order('id desc')->limit(3)->select();
        $this->assign([
            'user'=>$UserInfo,
            'total'=>$total,
            'Notice'=>$Notice,
            'team'=>$team,
        ]);
        return $this->fetch('Panel');
    }

    public function Feedback(){
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $Feedback = Db::name('feedback')->where(['user_id'=>$UserInfo['id']])->order('id desc')->select();
        $this->assign('Feedback',$Feedback);

        return $this->fetch('Feedback');
    }

    /**
     * 提交反馈
     * @return array|mixed
     */
    public function FeedbackAdd(){
        if(IsPost()){
            $AddData = [
                'user_id' => Session::get('user_id'),
                'content' => Param('content'),
                'add_time' => time(),
            ];

            if(Db::name('feedback')->insert($AddData)){
                return ['status'=>1,'message'=>'反馈已提交'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请稍后再试'];
            }
        }
        return $this->fetch('FeedbackAdd');
    }

    /**
     * Notes:我的等级
     * Time: 2022/1/14  16:38
     * User: Qian
     * @return mixed
     */
    public function UserLevel(){
        $UserInfo = UserInfo(['id'=>$this->user_id]);
        $LevelList = LevelList();
//        $end = '';
//        $end2 = '';
//        rsort($LevelList);
        foreach ($LevelList as $k=>$v){
//            $LevelList[$k]['range1'] = round($v['condition_1']).'~'.$end;
//            $LevelList[$k]['range2'] = round($v['condition_2']).'~'.$end2;
//            $end = round($v['condition_1']);
//            $end2 = round($v['condition_2']);
        }
//        sort($LevelList);
        $this->assign('LevelList',$LevelList);
        $this->assign('UserInfo',$UserInfo);
        return $this->fetch('UserLevel');
    }

    public function UserAdd(){
        $user = UserInfo(['id'=>$this->user_id]);
        if (IsPost()){
            $Data = Param();
            if (IsPost()){
                if ($Data['username'] == ''){
                    return ['status' => 0, 'message' => '请输入账号'];
                }
                if (!preg_match('/^(?!\d+$)(?![A-Za-z]+$)[a-zA-Z0-9]{2,}$/i',$Data['username'])){
                    return ['status' => 0, 'message' => '账号必须为字母+数字'];
                }
                $check_username = UserInfo(['username'=>$Data['username']]);
                if ($check_username){
                    return ['status' => 0, 'message' => '账号已存在'];
                }
                if ($Data['name'] == ''){
                    return ['status' => 0, 'message' => '请输入昵称'];
                }
                if (!preg_match('/^[^\s]*$/',$Data['name'])){
                    return ['status' => 0, 'message' => '昵称不能有空格'];
                }
                $check_name = UserInfo(['name'=>$Data['name']]);
                if ($check_name){
                    return ['status' => 0, 'message' => '昵称已存在'];
                }
                if ($Data['phone'] == ''){
                    return ['status' => 0, 'message' => '手机号不能为空'];
                }
                $check_phone = UserInfo(['phone'=>$Data['phone']]);
                if ($check_phone){
                    return ['status' => 0, 'message' => '手机号已存在'];
                }
                if (strlen($Data['pass_login']) < 6){
                    return ['status' => 0, 'message' => '登录密码至少6位'];
                }
                if (strlen($Data['pass_pay']) < 6){
                    return ['status' => 0, 'message' => '支付密码至少6位'];
                }
                $recommend = UserInfo(['recommend_num'=>$Data['recommend']]);
                if (!$recommend){
                    return ['status' => 0, 'message' => '邀请码不存在'];
                }
                $NumArr = Db::name('user')->column('recommend_num');
                do{
                    $recommend_num = randString();
                }while(in_array($recommend_num,$NumArr));

                $AddData = [
                    'username' => $Data['username'],   //账号
                    'name' => $Data['name'],   //账号
                    'phone' => $Data['phone'],   //账号
                    'password_login' => md5($Data['pass_login']),  //登录密码
                    'password_pay' => md5($Data['pass_pay']),  //支付密码
                    'status' => 1,    //账号状态 0未激活 1已激活 -1冻结
                    'recommend'=>$recommend['id'],    //推荐人ID
                    'recommend_num'=>$recommend_num,    //邀请码
                    'add_time'=>time(),    //注册时间
                ];
                if ($user_id = Db::name('user')->insertGetId($AddData)){
                    Db::query('call add_user_recommend(:id,:recommend_id)',['id'=>$user_id,'recommend_id'=>$recommend['id']]);    //创建推荐关系
                    Db::query('call user_uplevel(:user_id)',['user_id'=>$user_id]); //升级（推荐 团队 人数u）
                    //检查上级推荐人数 发放网图待发放奖励
                    CheckRecommendCount($recommend['id']);
                    return ['status' => 1, 'message' => '新增成功'];
                }else{
                    return ['status' => 0, 'message' => '新增失败'];
                }
            }
        }
        $this->assign('user',$user);
        return $this->fetch('UserAdd');
    }

    /**
     * Notes:网图
     * Time: 2021/12/28  10:53
     * User: Qian
     * @return mixed
     */
    public function UserMap(){
        $map = Db::name('user_map')->where(['user_id'=>$this->user_id,'status'=>1])->group('map_number')->select();
        foreach ($map as $k=>$v){
            $map[$k]['detail'] = Db::name('user_map')->alias('m')->join('zb_user u','m.user_id=u.id')
                ->where(['m.map_number'=>$v['map_number']])->field('m.user_id,m.map_level,m.position,u.username,u.recommend_num')->order('m.position asc')->select();
        }
        $this->assign('map',$map);
        $this->assign('user_id',$this->user_id);
        return $this->fetch('UserMap');
    }


    /**
     * Notes:个人中心
     * Time: 2021/12/28  15:14
     * User: Qian
     * @return mixed
     */
    public function UserInfo(){
        $UserInfo = UserInfo(['id'=>$this->user_id]);
        $LevelInfo = LevelInfo(['id'=>$UserInfo['level']]);
        if ($LevelInfo){
            $UserInfo['level_name'] = $LevelInfo['name'];
        }else{
            $UserInfo['level_name'] = '用户';
        }
        $url = "http://".$_SERVER['HTTP_HOST'].'/Open/Register?recommend='.$UserInfo['recommend_num'];
        $this->assign('UserInfo',$UserInfo);
        $this->assign('url',$url);
        return $this->fetch('UserInfo');
    }

    /**
     * Notes:修改登录密码
     * Time: 2021/12/29  16:49
     * User: Qian
     * @return mixed
     */
    public function UserPassLogin(){
        if(IsPost()){
            $Data = Param();
            $UserInfo = UserInfo(['id'=>$this->user_id]);

            if(md5($Data['old_password']) != $UserInfo['password_login']){
                return ['status'=>0,'message'=>'原密码错误'];
            }
            if(md5($Data['new_password']) == $UserInfo['password_login']){
                return ['status'=>0,'message'=>'新旧密码一致,无需更改'];
            }

            $SaveData['password_login'] = md5($Data['new_password']);
            if (Db::name('user')->where(['id'=>$UserInfo['id']])->update($SaveData) !== false){
                Session::delete('user_id');
                return ['status'=>1,'message'=>'修改成功','url'=>url('login')];
            }else{
                return ['status'=>0,'message'=>'无修改'];
            }
        }
        return $this->fetch('UserPassLogin');
    }

    public function UserPassPay(){
        $UserInfo = UserInfo(['id'=>$this->user_id]);
        if(IsPost()){
            $Data = Param();
            $UserInfo = UserInfo(['id'=>$this->user_id]);
            if ($UserInfo['password_pay'] != ''){
                if(md5($Data['old_password']) != $UserInfo['password_pay']){
                    return ['status'=>0,'message'=>'原密码错误'];
                }
            }

            if(md5($Data['new_password']) == $UserInfo['password_pay']){
                return ['status'=>0,'message'=>'新旧密码一致,无需更改'];
            }

            $SaveData['password_pay'] = md5($Data['new_password']);
            if (Db::name('user')->where(['id'=>$UserInfo['id']])->update($SaveData)){
                return ['status'=>1,'message'=>'修改成功'];
            }else{
                return ['status'=>0,'message'=>'无修改'];
            }
        }
        if ($UserInfo['password_pay'] != ''){
            $need = 1;
        }else{
            $need = 0;
        }
        $this->assign('need',$need);
        return $this->fetch('UserPassPay');
    }

    /**
     * Notes:网络图
     * Time: 2021/12/28  16:04
     * User: Qian
     * @return mixed
     */
    public function RecommendMap(){
        $UserInfo = UserInfo(['id'=>$this->user_id]);
//        $UserInfo = UserInfo(['id'=>1]);
        $where['recommend_id'] = $UserInfo['id'];
        $where['layer'] = ['neq',0];
        $team_count = Db::name('user_recommend')->where($where)->count();
        $list = Db::name('user_recommend')->alias('r')->join('zb_user u','r.user_id=u.id')
            ->where(['r.recommend_id'=>$this->user_id,'r.layer'=>['gt',0]])->field('u.*,r.layer')->paginate(1);
        $recommend = $list->toArray()['data'];
        foreach ($recommend as $k=>$v){
            if ($v['level'] > 0){
                $recommend[$k]['level_name'] = LevelInfo(['id'=>$v['level']])['name'];
            }else{
                $recommend[$k]['level_name'] = '用户';
            }
        }
        $this->assign('user',$UserInfo);
        $this->assign('recommend',$recommend);
        $this->assign('page',$list->render());
        $this->assign('team_count',$team_count);
        return $this->fetch('RecommendMap');
    }

    public function SelectSon_bak(){
        $pid = Param('pid');
        $where['recommend'] = $pid;
        $team1 = Db::name('user')->where($where)->select();
        return ReturnMsg(1,'',$team1);
    }

    public function RecommendMap2(){
        //查找的用户名
        $UserName = Param('username');
        if(empty($UserName)){
            $where['id'] = $this->user_id;
        }else{
            $where['username'] = $UserName;
        }
        //会员信息
        $UserInfo = UserInfo($where);
        if($UserInfo){
            $LevelInfo = LevelInfo(['id'=>$UserInfo['level']]);
            if ($LevelInfo){
                $UserInfo['level_name'] = $LevelInfo['name'];
            }else{
                $UserInfo['level_name'] = '用户';
            }
            $tips = $UserInfo['role'] == 1?'正常':'虚拟';
            $Data = array('name' =>$UserInfo['username'].'（'.$tips.'）|'.$UserInfo['level_name'],'children'=>$this->SelectSon($UserInfo['id']));       //父节点  Pid=1;
            $Data = json_encode($Data);
        }else{
            $Data = null;
        }
        $this->assign("Data",$Data);
        $this->assign("UserName",$UserName);
        return $this->fetch('RecommendMap2');
    }

    public  function SelectSon($Recommend){
        $Where['recommend'] = $Recommend;
        $UserList = Db::name('user')->where($Where)->select();
        if($UserList){  //查找该父ID下的子ID
            $Data = array();
            for ($i=0; $i < count($UserList) ; $i++)
            {
                $LevelInfo = LevelInfo(['id'=>$UserList[$i]['level']]);
                if ($LevelInfo){
                    $UserList[$i]['level_name'] = $LevelInfo['name'];
                }else{
                    $UserList[$i]['level_name'] = '用户';
                }
                $tips = $UserList[$i]['role'] == 1?'正常':'虚拟';
                $da=array('name' =>$UserList[$i]['username'].'（'.$tips.'）|'.$UserList[$i]['level_name'],'children'=>$this->SelectSon($UserList[$i]['id']));  //递归算法！

                array_push($Data, $da);//加入子节点数组
            };
            return $Data;//一次性返回子节点数组，他们成为同级子节点。
        } else{
            return null;
        }
    }

    /**
     * Notes:找直推人列表
     * Time: 2022/1/5  10:29
     * User: Qian
     */
    public function FindSon(){
        $recommend_id = Param('recommend_id');
        $max_layer = Db::name('user_recommend')->where(['recommend_id'=>$this->user_id,'user_id'=>$recommend_id])->value('layer');
        //上级
        $up = Db::name('user_recommend')->alias('r')->join('zb_user u','r.recommend_id=u.id')
            ->where(['r.user_id'=>$recommend_id,'r.recommend_id'=>['neq',1],'layer'=>['elt',$max_layer]])->field('r.recommend_id id,u.username')->order('r.layer desc')->select();

        $direct = Db::name('user')->where(['recommend'=>$recommend_id])->select();
        foreach ($direct as $k=>$v){
            $direct[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
        }

        $return['up'] = $up;
        $return['direct'] = $direct;

        return ReturnMsg(1,'',$return);
    }
}